<?php

namespace app\api\controller;

use app\api\model\Cart as CartModel;
use app\api\model\Goods as GoodsModel;
use app\api\model\Order as OrderModel;
use app\api\service\Bank;
use app\api\validate\order\Checkout as CheckoutValidate;
use app\common\enum\order\PayType as PayTypeEnum;

/**
 * 订单控制器
 * Class Order
 * @package app\api\controller
 */
class Order extends Controller
{
    /* @var \app\api\model\User $user */
    private $user;

    /* @var CheckoutValidate $validate */
    private $validate;

    /**
     * 订单结算api参数
     * @var array
     */
    private $checkoutParam = [
        'delivery' => null, // 配送方式
        'shop_id' => 0,     // 自提门店id
        'linkman' => '',    // 自提联系人
        'phone' => '',    // 自提联系电话
        'coupon_id' => 0,    // 优惠券id
        'remark' => '',    // 买家留言
        'pay_type' => PayTypeEnum::WECHAT,  // 支付方式
    ];

    /**
     * 构造方法
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function _initialize()
    {
        parent::_initialize();
        // 用户信息
        $this->user = $this->getUser();
        // 验证类
        $this->validate = new CheckoutValidate;
    }
    /****测试方法开始******/
    //银行交易成功后执行
    public function changePayStatus(){
        $param = $this->request->param();
        $order_no = $param['order_no'];
        // 获取商品结算信息
        $model = new OrderModel;
        $model->payOrder($order_no);
    }
    //银行提现成功后执行 收货
    public function changeCashStatus(){
        $param = $this->request->param();
        $order_no = $param['order_no'];
        // 获取商品结算信息
        $model = OrderModel::getOrderDetailByOrderNo($order_no);
        if ($model->receipt()) {
            return $this->renderSuccess();
        }
        return $this->renderError($model->getError());
    }
    //银行交易失败后执行
    public function changeStatus(){
        $param = $this->request->param();
        $order_no = $param['order_no'];
        $model = OrderModel::getOrderDetailByOrderNo($order_no);
        if ($model->cancels()) {
            return $this->renderSuccess($model->getError() ?: '订单取消成功');
        }
        return $this->renderError($model->getError() ?: '订单取消失败');
    }
    /****测试方法结束******/
    /**
     * 我的订单列表
     * @param $dataType  查询类型
     * @param $card_id  卡编号
     * @param $stage  阶段
     * @return array
     * @throws \think\exception\DbException
     */
    public function lists($dataType,$card_id,$stage)
    {
        $model = new OrderModel;
        $list = $model->getList($this->user['user_id'], $dataType,$stage,$card_id);
        return $this->renderSuccess(compact('list'));
    }

    /**
     * 订单详情信息
     * @param $order_id
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function detail($order_id)
    {
        // 订单详情
        $order = OrderModel::getUserOrderDetail($order_id, $this->user['user_id']);
        // 该订单是否允许申请售后
        $order['isAllowRefund'] = $order->isAllowRefund();
        return $this->renderSuccess(compact('order'));
    }

    /**
     * 会员申请提现
     */
    public function withdrawal(){
        $param = $this->request->param();
        $order_id = $param['order_id'];
        $model = new OrderModel;
        $model->updateToDelivery($order_id);
        //提交银行进行提现

    }

    /**
     * 订单确认-立即购买 用户提交交易订单
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     * @throws \Exception
     */
    public function buyNow()
    {
        // 请求的参数
        $params = $this->getCheckoutParams([
            'goods_id' => 10001,
            'goods_num' => 1,
            'goods_sku_id' => 0,
        ]);
        //选择产品 并计算相关手续费用
        $goods = $this->choiceGoods($params['totle_money']);
        $params['goods_id'] = $goods['good_id'];
        $params['service_money'] = $goods['service_money'];
        // 表单验证
        if (!$this->validate->scene('buyNow')->check($params)) {
            return $this->renderError($this->validate->getError());
        }
        // 获取商品结算信息
        $model = new OrderModel;
        $orderInfo = $model->getBuyNow($this->user, $params);

        if ($this->request->isGet()) {
            return $this->renderSuccess($orderInfo);
        }

        // submit：订单结算提交
        if ($model->hasError()) {
            return $this->renderError($model->getError());
        }

        // 创建订单
        if (!$model->createOrder($this->user, $orderInfo, $params)) {
            return $this->renderError($model->getError() ?: '订单创建失败');
        }

        // 支付状态提醒
        $message = ['success' => '提交成功'];
        return $this->renderSuccess([
            'order_id' => $model['order_id'],   // 订单id
            'pay_type' => $params['pay_type'],  // 支付方式
        ], $message);
    }

    /**
     * 根据价格选择产品
     * @param $totalprice
     * @return mixed
     * @throws \app\common\exception\BaseException
     */
    private function choiceGoods($totalprice){
        $paras['good_id'] = $totalprice<1000?10001:10002;
        // 商品详情
        $goods = GoodsModel::getDetails($paras['good_id']);
        // 商品sku信息
        $goods_sku = GoodsModel::getGoodsSku($goods, 0);
        //产品费率 $goods_sku['goods_price'];
        //产品手续费 $goods_sku['line_price'];
        $paras['service_money'] = ($totalprice*$goods_sku['goods_price']*0.01)+$goods_sku['line_price'];
        return $paras;
    }



    /**
     * 订单确认-购物车结算
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \Exception
     */
    public function cart()
    {
        // 请求的参数
        $params = $this->getCheckoutParams([
            'cart_ids' => '',
        ]);
        // 商品结算信息
        $CartModel = new CartModel($this->user);
        // 购物车商品列表
        $goodsList = $CartModel->getList($params['cart_ids']);
        // 获取订单结算信息
        $orderInfo = (new OrderModel)->getCart($this->user, $params, $goodsList);
        if ($this->request->isGet()) {
            return $this->renderSuccess($orderInfo);
        }
        // 创建订单
        $model = new OrderModel;
        if (!$model->createOrder($this->user, $orderInfo, $params)) {
            return $this->renderError($model->getError() ?: '订单创建失败');
        }
        // 移出购物车中已下单的商品
        $CartModel->clearAll($params['cart_ids']);
        // 构建微信支付请求
        $payment = $model->onOrderPayment($this->user, $params['pay_type']);
        // 返回状态
        return $this->renderSuccess([
            'order_id' => $model['order_id'],   // 订单id
            'pay_type' => $params['pay_type'],  // 支付方式
            'payment' => $payment               // 微信支付参数
        ]);
    }

    /**
     * 订单结算提交的参数
     * @param $define
     * @return array
     */
    private function getCheckoutParams($define)
    {
        return array_merge($this->checkoutParam, $define, $this->request->param());
    }

}
